﻿const fs=require('fs');
const jsonServer = require("json-server");
const { createServer } = require('node:http');

// const server = jsonServer.create(); //集成express，使用下面三行代替
var express = require('express');
const app=express()
const server = createServer(app);

const middlewares = jsonServer.defaults();

//socket.io
const { Server } = require('socket.io');
// const io = new Server(server); 
const io = new Server(server,{cors:true}); //允许跨域
const config = require('./config/config.default');//保存全局变量
io.on('connection', (socket) => {
  config.sockets.push(socket)
  console.log('a user connected');
  socket.emit('msg','连接到服务成功');
  //监听电脑修改柜门绑定的车组号
  socket.on('updated',(data)=>{
    console.log('update***:');
    console.log(data);
    config.sockets.forEach(s=>{
      if(s.id!==socket.id){
        //向其他客户端发送修改的柜门绑定车组
        s.emit('updated',data)
      }
    })
  })
  socket.on('disconnect', () => {
      config.sockets=config.sockets.filter(s=>s.id!==socket.id);
      console.log('user disconnected');
    });
});


//api子路由
app.use('/api', require('./router/api/index'));

app.get('/json/locks', (req, res) => {
  // const locks=require('./nndb.json').locks
  fs.readFile('./nndb.json', 'utf8', (err, data) => {
    if (err) {
      return res.status(500).send('Error reading data.json');
    }
    const locks=JSON.parse(data).locks
    locks.forEach((lock,index)=>{
      if(lock.is400AF){
        locks[index].czh='S'+locks[index].czh
      }
      delete locks[index].is400AF
    })
    res.send(locks)
  });
  
});


//json-server功能：读取的json数据库生成的默认路由：注意不要被上面的自定义路由覆盖了
app.use(middlewares);
const router = jsonServer.router(config.db);
app.use('/json2',router);


//静态目录 http://localhost:3000/static/index.html
app.use('/static',express.static('public'))

server.listen(3000, () => {
  console.log("JSON Server is running 3000 连接数"+config.sockets.length);
});
